package com.dreamer.view.sub;

import com.dreamer.domain.pmall.goods.PmallGoods;
import com.dreamer.domain.pmall.goods.PmallGoodsType;
import com.dreamer.domain.sub.SubGoods;
import com.dreamer.domain.user.AgentLevel;
import com.dreamer.domain.user.User;
import com.dreamer.repository.mall.goods.MallGoodsDAO;
import com.dreamer.repository.mall.goods.MallGoodsTypeDAO;
import com.dreamer.repository.mobile.AgentLevelDao;
import com.dreamer.repository.sub.SubGoodsDAO;
import com.dreamer.service.mobile.MallGoodsHandler;
import com.dreamer.service.sub.SubGoodsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ps.mx.otter.exception.NotAuthorizationException;
import ps.mx.otter.utils.WebUtil;
import ps.mx.otter.utils.message.Message;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/sub/goods")
public class SubGoodsController {

	@RequestMapping(value = "/edit.json", method = {RequestMethod.POST,RequestMethod.PUT})
	public Message edit(
			@ModelAttribute("parameter") PmallGoods parameter, @RequestParam(value="img",required=false) MultipartFile file, @RequestParam(value = "wallImg",required = false) MultipartFile wallFile,
			HttpServletRequest request, Integer mType,Integer level, Integer[] ids, String[] standardNames, Double[] standardPrices, Integer[] standardStocks) {

		try{
			User user = (User) WebUtil.getCurrentUser(request);
//			if (!user.isAdmin()) {
//				LOG.error("非管理员身份,无置换商城商品编辑权限");
//				throw new NotAuthorizationException();
//			}
			PmallGoodsType pmallGoodsType = mallGoodsTypeDAO.findById(mType);
			parameter.setGoodsType(pmallGoodsType);
			AgentLevel agentLevel = agentLevelDao.get(level);
			parameter.setLevel(agentLevel);
			/*if(parameter.getStatus() == null || parameter.getStatus().equals("")){
				//todo 置换商城新增的商品状态默认为：审核中
				parameter.setStatus(2);
				*//*parameter.setSubGoods("置换商城");*//*
			}
            if(parameter.getStatus() != null && parameter.getStatus() == 1){
                //todo 置换商城新增的商品状态默认为：审核中
                parameter.setStatus(2);
            }*/
			/*if(parameter.getUser() == null || parameter.getUser().getRealName().equals("")){
				//todo set当前上传者
				parameter.setUser(user);
				*//*parameter.setSubGoods("置换商城");*//*
			}*/
			String imgType  = null;
			String wallType =null;
			byte[] imgBytes =null;
			byte[] wallBytes =null;
			if(!Objects.isNull(file)&&!file.isEmpty()){
				imgType =getImgType( file.getOriginalFilename());
				imgBytes = file.getBytes();
			}
			if(!Objects.isNull(wallFile)&&!wallFile.isEmpty()){
				wallType =getImgType( wallFile.getOriginalFilename());
				wallBytes=wallFile.getBytes();
			}
			mallGoodsHandlers.addMallGoods(parameter,imgType,wallType,imgBytes,wallBytes,ids,standardNames,standardPrices,standardStocks);
//				if(Objects.isNull(file)||file.isEmpty()){
//					mallGoodsHandler.modifyMallGoods(parameter,null,null);
//				}else{
//					String imgType =getImgType(file.getOriginalFilename());
//					mallGoodsHandler.modifyMallGoods(parameter,imgType,file.getBytes());
//				}
			return Message.createSuccessMessage();
		}catch(Exception exp){
			exp.printStackTrace();
			LOG.error("置换商城商品维护失败",exp);
			return Message.createFailedMessage(exp.getMessage());
		}
	}


	/**
	 * 商品审核
	 * @param parameter
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/audit.json", method = RequestMethod.POST)
	public Message audit(
			@ModelAttribute("parameter") PmallGoods parameter, HttpServletRequest request) {
		try{
			User user = (User) WebUtil.getCurrentUser(request);
			if (!user.isAdmin()) {
				LOG.error("非管理员身份,无置换商城商品编辑权限");
				throw new NotAuthorizationException();
			}
//			SubGoods subGoods = mallGoodsDAO.findById(parameter.getId());
//            subGoods.setStatus(0);
			if(parameter.getId() == null || parameter.getId().equals("")){
				/*parameter.setSubGoods("置换商城");*/
			}
			mallGoodsHandlerss.saveOrUpdate(parameter);
			return Message.createSuccessMessage();
		}catch(Exception exp){
			exp.printStackTrace();
			LOG.error("置换商城商品维护失败",exp);
			return Message.createFailedMessage(exp.getMessage());
		}
	}

	private String getImgType(String name){
		return name.substring(name.indexOf("."));
	}

	@ResponseBody
	@RequestMapping(value = "/remove.json", method = {RequestMethod.DELETE})
	public Message delete(
			@ModelAttribute("parameter") PmallGoods parameter,
			HttpServletRequest request, Model model) {		
		try{
			User user = (User) WebUtil.getCurrentUser(request);
//			if (!user.isAdmin()) {
//				LOG.error("非管理员身份,无置换商城商品编辑权限");
//				throw new NotAuthorizationException();
//			}
			mallGoodsHandlers.removeMallGoods(parameter);
			return Message.createSuccessMessage();
		}catch(Exception exp){
			exp.printStackTrace();
			LOG.error("置换商城商品删除失败",exp);
			return Message.createFailedMessage(exp.getMessage());
		}
	}
	


	@ModelAttribute("parameter")
	public PmallGoods preprocess(
			@RequestParam("id") Optional<Integer> id) {
		PmallGoods goods = null;
		if (id.isPresent()) {
			goods = mallGoodsDAOs.findById(id.get());
		} else {
			goods = new PmallGoods();
		}
		return goods;
	}

	@Autowired
	private SubGoodsDAO mallGoodsDAO;
	@Autowired
	private MallGoodsTypeDAO mallGoodsTypeDAO;
	@Autowired
	private SubGoodsHandler mallGoodsHandler;
	@Autowired
	com.dreamer.service.mobile.SubGoodsHandler subGoodsHandler;

	@Autowired
	private MallGoodsDAO mallGoodsDAOs;

	@Autowired
	private com.dreamer.service.mall.goods.MallGoodsHandler mallGoodsHandlers;
	@Autowired
	private MallGoodsHandler mallGoodsHandlerss;

	@Autowired
	private AgentLevelDao agentLevelDao;

	private final Logger LOG = LoggerFactory.getLogger(getClass());

}
